//
//  YXPlayerResourceLoader.swift
//  swift_wobo
//
//  Created by yuxin on 2018/12/2.
//  Copyright © 2018 wuxiantianli. All rights reserved.


//注：一个YXPlayerResourceLoader绑定一个视频url

import UIKit
import AVFoundation
import MobileCoreServices

protocol YXPlayerResourceLoaderDelegate: class {
     func playerResourceLoader(_ loader: YXPlayerResourceLoader, didCompleteWithError error: Error?)
}

class YXPlayerResourceLoader: NSObject {
    ///seek标识
    var isSeek = false
    var isCancel = false

    private var requestManger: YXPlayerRequestManger
    private var downloadManger: YXPlayerDownloadManger
    
    
    
    weak var delegate: YXPlayerResourceLoaderDelegate?
    
    init(url: URL) {
        requestManger = YXPlayerRequestManger()
        downloadManger = YXPlayerDownloadManger(url: url)
        super.init()
        downloadManger.delegate = self
    }
    
    func append(loadingRequest request: AVAssetResourceLoadingRequest){

        startWork(request: request)
        
    }
    
    func cancel() {
        cancelAll()
    }
    
    func remove(loadingRequest request: AVAssetResourceLoadingRequest){
        
        requestManger.remove(loadingRequest: request)
        
    }
    
}


// 只保留最新一次请求
extension YXPlayerResourceLoader {
    private func startWork(request: AVAssetResourceLoadingRequest) {
        requestManger.add(loadingRequest: request)
        let requesRange = requestManger.currentRange()
        downloadManger.start(forRange: requesRange)
        isCancel = false
    }
    
    private func cancelAll() {
        requestManger.cancel()
        downloadManger.cancel()
        isCancel = true
    }
}

extension YXPlayerResourceLoader: YXPlayerDownloadMangerDelegate {
    
    func download(downloadManger: YXPlayerDownloadManger, didReceiveResponse response: URLResponse) {
        
    }
    
    func download(downloadManger: YXPlayerDownloadManger, didReceiveData data: Data) {
        requestManger.loadingRequest?.dataRequest?.respond(with: data)
    }
    
    func download(downloadManger: YXPlayerDownloadManger, didFinishedWithError error: Error?) {
        if error?._code == NSURLErrorCancelled { return }
        
        if (error == nil) {
            requestManger.loadingRequest?.finishLoading()
        } else {
            requestManger.loadingRequest?.finishLoading(with: error)
        }
        
        delegate?.playerResourceLoader(self, didCompleteWithError: error)
    }

}

extension YXPlayerResourceLoader {
    
    private func mergeRequest(request: AVAssetResourceLoadingRequest) {
        let currentRange = (requestManger.requestOffset...(requestManger.requestOffset + requestManger.cacheLength))
        if currentRange.contains((request.dataRequest?.requestedOffset)!) {
            print("数据已经缓存，则直接完成")
            processRequestList()
        }else {
            //数据还没缓存，则等待数据下载；如果是Seek操作，则重新请求
            if isSeek {
                print("Seek操作，重新请求")
                newRequest(loadingRequest: request)
            }
        }
    }
    
    private func newRequest(loadingRequest: AVAssetResourceLoadingRequest) {
//        var fileLength: Int64 = requestManger.fileLength
//        requestManger.isCancel = true
        
//
//
//        requestManger = YXPlayerRequestManger(url: loadingRequest.request.url!)
//        requestManger?.requestOffset = (loadingRequest.dataRequest?.requestedOffset)!
//
//        if fileLength > 0 {
//            requestManger?.fileLength = fileLength
//        }
//
//        requestManger?.delegate = self
//        requestManger?.start()
        isSeek = false
    }
    
    private func processRequestList() {
//        requestList = requestList.filter({ (request) -> Bool in
//            return !finishLoadingWithLoadingRequest(loadingRequest: request)
//        })
    }
    
    private func finishLoadingWithLoadingRequest(loadingRequest: AVAssetResourceLoadingRequest) -> Bool {
        let mimeType = "video/mp4" as CFString
        let contentType =  UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, nil)
        
        if let takeUnretainedValue = contentType?.takeUnretainedValue() {
            loadingRequest.contentInformationRequest?.contentType = takeUnretainedValue as String
        }
//
//        loadingRequest.contentInformationRequest?.isByteRangeAccessSupported = true
//        loadingRequest.contentInformationRequest?.contentLength = (requestManger?.fileLength)!
//
//        let cacheLength = requestManger?.cacheLength
//        var requestedOffset = loadingRequest.dataRequest?.requestedOffset
//
//        if loadingRequest.dataRequest?.currentOffset != 0 {
//            requestedOffset = loadingRequest.dataRequest?.currentOffset
//        }
//
//
//        let canReadLength = cacheLength! - (requestedOffset! - (requestManger?.requestOffset)!)
//        var respondLength = cacheLength
//        if cacheLength > loadingRequest.dataRequest?.requestedLength {
//            respondLength = loadingRequest.dataRequest?.requestedLength
//        }
//
//        loadingRequest.dataRequest?.respond(with: <#T##Data#>)
//
//
//
//
//        [loadingRequest.dataRequest respondWithData:[SUFileHandle readTempFileDataWithOffset:requestedOffset - self.requestTask.requestOffset length:respondLength]];
//
//        //如果完全响应了所需要的数据，则完成
//        NSUInteger nowendOffset = requestedOffset + canReadLength;
//        NSUInteger reqEndOffset = loadingRequest.dataRequest.requestedOffset + loadingRequest.dataRequest.requestedLength;
//        if (nowendOffset >= reqEndOffset) {
//            [loadingRequest finishLoading];
//            return YES;
//        }
//        return NO;
        
        
        return false
    }
    
}



